package org.blackjuly.sign.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtil {
	
	/**
	 * 将源对象属性复制给目标对象
	 * @param src   源对象
	 * @param dest  目标对象
	 */
	public static void copyProperties(Object src, Object target) {
		Class<?> srcClass, targetClass;
		Field[] srcFields;
		Method[] srcMethods, targetMethods;
		Map<String, Method> srcMethodMap = new HashMap<>();
		Map<String, Method> targetMethodMap = new HashMap<>();
		
		srcClass = src.getClass();
		targetClass = target.getClass();
		srcFields = srcClass.getDeclaredFields();
		srcMethods = srcClass.getMethods();
		targetMethods = targetClass.getMethods();
		
		for (Method method : srcMethods) {
			srcMethodMap.put(method.getName(), method);
		}
		for (Method method : targetMethods) {
			targetMethodMap.put(method.getName(), method);
		}
		
		for (Field field : srcFields) {
			// 判断源对象是否有get方法，目标对象是否有set方法
			Method srcGetMethod = srcMethodMap.get("get" + StringUtil.letter(field.getName()));
			Method targetSetMethod = targetMethodMap.get("set" + StringUtil.letter(field.getName()));
			if (srcGetMethod == null || targetSetMethod == null)
				continue;
			try {
				Object value = srcGetMethod.invoke(src);
				targetSetMethod.invoke(target, value);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}